package org.sean.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.sean.framework.util.StringUtil;
import org.sean.generator.form.Page;
import org.sean.generator.form.Query;
import org.sean.generator.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController {
    @Autowired
    private GeneratorService generatorService;
    @Autowired
    DynamicRoutingDataSource dynamicDataSource;

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public Page list(@RequestParam Map<String, Object> params) {
        String dsId = params.get("ds") == null ? null : params.get("ds").toString();
        pushDS(dsId);
        try {
            return generatorService.queryList(new Query(params));
        } finally {
            pollDS(dsId);
        }
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(String ds, String tables, String fc, String groupId, String artifactId, String tp, HttpServletResponse response)
            throws IOException {
        pushDS(ds);
        try {
            byte[] data = generatorService.generatorCode(Boolean.parseBoolean(fc), groupId, artifactId, tables.split(","), tp);

            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + artifactId + ".zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");

            IoUtil.write(response.getOutputStream(), false, data);
        } finally {
            pollDS(ds);
        }
    }

    private void pushDS(String dsId) {
        if (StringUtil.isNotEmpty(dsId)) {
            DynamicDataSourceContextHolder.push(dsId);
        }
    }

    private void pollDS(String dsId) {
        if (StringUtil.isNotEmpty(dsId)) {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
